/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.secure;

import java.util.List;

import lombok.AllArgsConstructor;

import org.moon.framework.autoconfigure.secure.aop.AuthAspect;
import org.moon.framework.autoconfigure.secure.aop.FormRepeatSubmitAspect;
import org.moon.framework.autoconfigure.secure.aop.SecureInterceptor;
import org.moon.framework.autoconfigure.secure.props.SecureProperties;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.cache.CacheService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 安全配制
 * @author moon
 */
@Configuration
@EnableConfigurationProperties({SecureProperties.class})
public class SecureAutoConfiguration {
	
	@Configuration
	@AllArgsConstructor
	public class SecureConfiguration implements WebMvcConfigurer {
		private CacheService cacheService;
		private final SecureProperties secureProperties;

		@Override
		public void addInterceptors(InterceptorRegistry registry) {
			//默认开启
			if(secureProperties.getTokenEnabled()!=null && secureProperties.getTokenEnabled()==false){
				return;
			}
			//TODO 暂时不考虑客户端验证
//			clientProperties.getClient().forEach(cs -> registry.addInterceptor(new ClientInterceptor(cs.getClientId())).addPathPatterns(cs.getPathPatterns()));
			//uri 拦截
			List<String> defaultExcludePatterns = MoonConstants.STATIC_RESOUCE;
			registry.addInterceptor(new SecureInterceptor(cacheService))
					.excludePathPatterns(defaultExcludePatterns)
					.excludePathPatterns(secureProperties.getExcludePatterns());
		}
	}
	@Bean
	@ConditionalOnProperty(value = "moon.security.auth-enabled",matchIfMissing=true)
	public AuthAspect authAspect() {
		return new AuthAspect();
	}

	@Bean
	@ConditionalOnProperty(value = "moon.security.form-repeat-enabled",matchIfMissing=true)
	public FormRepeatSubmitAspect formRepeatSubmitAspect() {
		return new FormRepeatSubmitAspect();
	}
}